import Foundation

func startServerInBackground() {
    let executablePath = CommandLine.arguments[0]
    
    let task = Process()
    task.executableURL = URL(fileURLWithPath: executablePath)
    task.arguments = ["server"]
    
    // 重定向输出到 /dev/null 以在后台运行
    task.standardOutput = FileHandle.nullDevice
    task.standardError = FileHandle.nullDevice
    task.standardInput = FileHandle.nullDevice
    
    do {
        try task.run()
        // 等待一小段时间确保服务器启动
        usleep(500000) // 0.5秒
        
        if isServerRunning() {
            print("✅ VDH server started successfully in background")
            print("📡 Socket: /tmp/video_downloader.sock")
            print("🗃️ Database: ~/.vdh/video_downloader.db")
        } else {
            print("❌ Failed to start VDH server")
            exit(1)
        }
    } catch {
        print("❌ Failed to start server: \(error)")
        exit(1)
    }
}

func stopServer() {
    // 发送停止信号到服务器
    if sendToSocket(url: "SHUTDOWN") {
        // 等待服务器关闭
        usleep(500000) // 0.3秒
        
        if !isServerRunning() {
            print("✅ VDH server stopped successfully")
        } else {
            print("⚠️ Server may still be running, trying force stop...")
            // 尝试通过进程名终止
            let task = Process()
            task.executableURL = URL(fileURLWithPath: "/usr/bin/pkill")
            task.arguments = ["-f", "vdh server"]
            
            do {
                try task.run()
                task.waitUntilExit()
                
                usleep(300000) // 0.3秒
                if !isServerRunning() {
                    print("✅ VDH server force stopped")
                } else {
                    print("❌ Failed to stop VDH server")
                }
            } catch {
                print("❌ Failed to force stop server: \(error)")
            }
        }
    } else {
        print("❌ Could not communicate with server to stop it")
        // 直接尝试终止进程
        let task = Process()
        task.executableURL = URL(fileURLWithPath: "/usr/bin/pkill")
        task.arguments = ["-f", "vdh server"]
        
        do {
            try task.run()
            task.waitUntilExit()
            print("✅ VDH server process terminated")
        } catch {
            print("❌ Failed to terminate server process: \(error)")
        }
    }
}

func checkServerStatus() {
    if isServerRunning() {
        print("✅ VDH server is running")
        print("📡 Socket: /tmp/video_downloader.sock")
        print("🗃️ Database: ~/.vdh/video_downloader.db")
        
        // 获取队列状态
        print("\n📊 Queue Status:")
        if sendStatusRequest() {
            // Status已经在sendStatusRequest中打印了
        } else {
            print("❌ Could not retrieve queue status")
        }
        
        // 获取统计信息
        print("\n📈 Statistics:")
        let helper = VideoDownloaderHelper()
        let stats = helper.dbManager.getTaskStats()
        for status in TaskStatus.allCases {
            let count = stats[status] ?? 0
            let emoji = helper.getStatusEmoji(status)
            print("  \(emoji) \(status.rawValue.capitalized): \(count)")
        }
        let total = stats.values.reduce(0, +)
        print("  📋 Total: \(total)")
        
    } else {
        print("❌ VDH server is not running")
        print("💡 Start with: vdh start")
    }
}